package com.pmmaster.common.utils;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

public class HttpsUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtils.class);
    private static final String DEFAULT_CHAR_SET = "UTF-8";
    private static final String USER_AGENT = "Mozilla/5.0";

    /**
     * 以get方式发送https请求，获取响应的JSON字符窜
     * @param url 请求的基于https的url
     * @return 返回url响应的JSON字符窜
     */
    public static String get(String url) {
        HttpsURLConnection https = null;

        try {
            https = (HttpsURLConnection) new URL(url).openConnection();
            if(null != https){
                https.setRequestMethod(Method.GET.name());
                https.setRequestProperty("User-Agent", USER_AGENT);
                return read(https, DEFAULT_CHAR_SET);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * 通过post提交数据到指定的url，数据默认以UTF-8编码
     * @param url　请坟的基于https的url
     * @param message 提交的内容
     * @return　返回url响应的message
     */
    public static String post(String url, String message) {
        HttpsURLConnection https = null;
        String msg = null;
        try {
            https = (HttpsURLConnection) new URL(url).openConnection();
            https.setSSLSocketFactory(createDefaultSSLSocketFactory());
            https.setDoInput(true);
            https.setDoOutput(true);

            https.setRequestMethod(Method.POST.name());

            write(https, message);

            msg = https.getResponseMessage();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return msg;
    }

    /**
     * 发送https请求
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("连接超时：{}" + ce.getMessage());
        } catch (Exception e) {
            logger.error("https请求异常：{}" + e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 创建一个默认的，空的信任管理工厂
     * @return 返回创建的信任管理工厂
     */
    private static SSLSocketFactory createDefaultSSLSocketFactory() {
        TrustManager[] tm = {new DefaultX509TrustManager()};
        SSLContext sslContext = null;
        SSLSocketFactory factory = null;
        try {
            sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());

            factory = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage());
        } catch (NoSuchProviderException e) {
            logger.error(e.getMessage());
        } catch (KeyManagementException e) {
            logger.error(e.getMessage());
        }

        if(null == factory) {
            throw new RuntimeException("SSLSocketFactory is null");
        }

        return factory;
    }
    /**
     * 从流中读取数据
     * @param https
     * @param chaset
     * @return
     */
    private static String read(HttpsURLConnection https, String chaset) {
        chaset = StringUtil.isBlank(chaset) ? DEFAULT_CHAR_SET : chaset;
        BufferedReader in = null;
        StringBuilder msg = new StringBuilder();
        try {
            if(HttpsURLConnection.HTTP_OK == https.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(https.getInputStream(), chaset));
                String str;
                while ((str = in.readLine()) != null) {
                    msg.append(str);
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return msg.toString();
    }

    /**
     * 通过默认的UTF-8编码，写数据到对应的流
     * @param https
     * @param msg 写出的消息
     */
    private static void write(HttpsURLConnection https, String msg) {
        write(https,msg,null);
    }

    /**
     * 写数据到对应的流
     * @param https
     * @param msg 写出的消息
     * @param charset 写出消息的编码
     */
    private static void write(HttpsURLConnection https, String msg, String charset) {
        charset = null == charset || "" == charset ? DEFAULT_CHAR_SET : charset;
        BufferedWriter out = null;

        try {
            out = new BufferedWriter(new OutputStreamWriter(https.getOutputStream(), charset));

            out.write(msg);
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (null != out) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

    enum Method {
        GET, PUT, POST, DELETE
    }
}

